package ru.papergames.model.proxies
{
	import ru.papergames.controller.notifications.FrontendNotifications;
	import ru.papergames.model.vo.LoginVO;
	import ru.papergames.utils.constants.ConfigKeys;
	
	public class LoginProxy extends MainHTTPProxy
	{
		
		public static const NAME:String = 'LoginProxy';
		
		//methods
		public static const LOGIN:String = 'login';
		
		//responses
		public static const LOGIN_START:String = LOGIN + HTTPProxy.START_NOTE_POSTFIX;
		public static const LOGIN_SUCCESS:String = LOGIN + HTTPProxy.SUCCESS_NOTE_POSTFIX;
		public static const LOGIN_FAULT:String = LOGIN + HTTPProxy.FAULT_NOTE_POSTFIX;
		
		
		private var logoutProxy:LogoutProxy;
		
		public function LoginProxy(url:String)
		{
			super(NAME, url, new LoginVO());
			this.useOperationParam = false;
		}
		
		override public function onRegister():void {
			super.onRegister();
			logoutProxy = new LogoutProxy(this.settingsProxy.getProperty(ConfigKeys.LOGOFF_URL), loginVO);
			facade.registerProxy(logoutProxy);
		}
		
		override public function onRemove():void {
			facade.removeProxy(LogoutProxy.NAME);
			
			logoutProxy = null;
			
			super.onRemove();
			
			this.setData(null);
		}
				
		public function get loginVO():LoginVO {
			return this.data as LoginVO;
		}
		
		public function doLogin(lvo:LoginVO):void {
			loginVO.fillFromObject(lvo);
			call(LOGIN, lvo.postObject);
		}
		
		public function doLogout():void {
			logoutProxy.call(LogoutProxy.LOGOUT);
		}
		
		override protected function parseResponse(data:XML, ownResponse:Boolean):void {
			if (data.data.login.toString())  {
				loginVO.username = String(data.data.login);
			}
			
			if (data.data.pers_creation.toString())  {
				loginVO.needPersCreation = String(data.data.pers_creation) == 'true';
			}
		}
		
		/*****  Call handlers  *****/
		
		/* Login */		
		public function login_Result(data:XML):String {
			loginVO.isLoggedIn = String(data.data.success) == 'true';
						
			return loginVO.isLoggedIn ? LOGIN_SUCCESS : LOGIN_FAULT;
		}
		
	}
}